<!--
 * @Author: yfp
 * @Date: 2024-03-30 20:00:53
 * @LastEditors: yehongbo 1394168736@qq.com
 * @LastEditTime: 2024-07-23 18:53:53
 * @Description: 
-->


<template>
  <!-- <div class="mask" v-if="showMask"></div> -->
  <div class="box-content">
    <el-table :data="pageData" :header-cell-style="tableColor" style="width: 100%" :height="tableH">
      <el-table-column type="index" width="80" label="序号" align="center">
        <template #default="scope">
          {{ (scope.$index + 1) + (currentPage - 1) * pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="send_time" label="上传时间" align="center" />
      <!-- <el-table-column prop="file_name" label="文件名称" align="center"/> -->
      <el-table-column prop="out_file" label="文件名称" align="center" show-overflow-tooltip />
      <el-table-column prop="time_range" label="时间范围" width="320" align="center" show-overflow-tooltip />
      <el-table-column prop="num" label="信号总数" align="center" />
      <!-- <el-table-column prop="num" label="定值修改次数" align="center" /> -->
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <span v-if="row.status == 1" style="color: orange">{{
            formatterStatus(row.status)
          }}</span>
          <span v-else-if="row.status == -1" style="color: red">{{
            formatterStatus(row.status)
          }}</span>
          <span v-else style="color: green">{{
            formatterStatus(row.status)
          }}</span>
        </template>
        <!-- :formatter="formatterStatus" -->
      </el-table-column>
      <!-- <el-table-column label="状态">
      <template #default="{ row }">
        <el-progress :percentage="getProgress(row)" :format="formatProgress"></el-progress>
      </template>
    </el-table-column> -->
      <el-table-column label="结果查看" width="180" align="center">
        <template #default="{ row }">
          <!-- <el-button v-if="row.status == 0" link type="primary" size="small" @click="handleClick(row)">查看</el-button>
          <el-button v-if="row.status == 0" link type="danger" size="small" @click="deleteClick(row)">删除</el-button> -->
          <el-tag v-if="row.status == 0" @click="handleClick(row)" style="background-color:#f2f3f5;">查看</el-tag>
          <el-tag v-if="row.status == 0" @click="deleteClick(row)" style="color:red;background-color:#f2f3f5;">删除</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-box">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- http://192.168.20.201:8088/api/send_predict -->
    <!-- action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" -->
    <div class="button-div">
      <el-upload ref="uploadRef" :disabled="uploadComplete" v-model:file-list="fileList" class="upload-box" action="#"
        :multiple="false" :on-success="handleSuccess" :on-error="handleError" :on-progress="handleProgress"
        :on-change="handleChange" :limit="1" :show-file-list="false" accept=".xlsx,.xls,.csv" :data="uploadData"
        :http-request="uploadFile" :auto-upload="true" :on-exceed="handleExceed">
        <!-- :auto-upload="false" -->
        <!--  -->
        <el-button type="primary" class="button_class blue">上传文件</el-button>
      </el-upload>
      <el-button @click="downloadExcel" class="button_class gray">下载示例文件</el-button>
    </div>

    <!-- :indeterminate="true"  -->
    <!-- <el-progress v-if="progressFlag" :stroke-width="15" :duration="10" :striped-flow="true" :indeterminate="true" :percentage="loadProgress"></el-progress> -->
    <el-progress style="margin-top: 20px" v-if="progressFlag" :stroke-width="15" :duration="10" :striped-flow="true"
      striped :percentage="loadProgress"></el-progress>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick, onBeforeMount } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import hisRecord from "@/api/hisRecord";

// 上传中 推理中 已完成
const tableData = ref([]);
let pageData = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const uploadRef = ref();

let total = ref(1);
let tableH = ref(0);
const tableColor = {
  backgroundColor: '#F2F3F5',
  borderColor: '#F2F3F5',
}
onMounted(async () => {
  nextTick(() => {
    console.log('window.innerHeight', window.innerHeight)
    tableH.value = window.innerHeight - 280
  });
  await onLoad();
});

/** 加载数据 */
const onLoad = () => {
  hisRecord
    .getHisRecordList({ token: localStorage.getItem('accessToken') })
    .then((res) => {
      console.log(res);
      // 1:正常；0:异常；
      if (res && res.data.code === 1) {
        tableData.value = [];
        if (res.data.data.data) {
          for (const key in res.data.data.data) {
            const obj = res.data.data.data[key];
            tableData.value.push(obj);
          }
        } else {
          tableData.value = [];
        }
        console.log("数据", tableData.value);
        pageData.value = getPagedData();
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// 计算分页后的数据
const getPagedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  total.value = tableData.value.length;
  return tableData.value.slice(start, end);
};

// 下载文件
const downloadExcel = () => {
  hisRecord.downloadFile("shili.xlsx").then((res) => {
    const blobData = new Blob([res.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });
    // debugger;
    // const url = window.URL.createObjectURL(blobData);
    var downloadElement = document.createElement("a");

    var href = window.URL.createObjectURL(blobData);

    downloadElement.href = href;

    downloadElement.download = `shili.xlsx`;

    document.body.appendChild(downloadElement);

    downloadElement.click();

    document.body.removeChild(downloadElement);

    window.URL.revokeObjectURL(href);
  });
};

// row, column,
const formatterStatus = (cellVal) => {
  let text = "";
  switch (cellVal) {
    case 1:
      text = "推理中";
      break;
    case 0:
      text = "已完成";
      break;
    case -1:
      text = "推理失败";
      break;
  }
  return text;
};
let showMask = ref(false);
const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  currentPage.value = 1;
  pageSize.value = val;
  pageData.value = getPagedData();
};

const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  pageData.value = getPagedData();
};
// 添加文件、上传成功、上传失败都会被调用
const handleChange = () => { };
// 下方表格逻辑
const handleClick = (row) => {
  // 筛选上面表格数据
  console.log("click", row);
  const time = new Date().getTime();
  emit("tabVal", true, row.out_file, row.out_file, time);
  // emit("changeStep", true);
};
const deleteClick = (row) => {
  ElMessageBox({
    title: "系统提示",
    message: '是否删除当前数据？',
    type: "warning",
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        console.log('delete row', row)
        hisRecord
          .deleteData({ id: row.id })
          .then((res) => {
            console.log(res);
            // 1:正常；0:异常；
            if (res && res.data.code === 1) {
              ElMessage({
                type: 'success',
                message: '删除成功'
              })
              onLoad()
            } else {
              ElMessage({
                type: 'warning',
                message: res.data.msg
              })
            }
          })
          .catch((err) => {
            ElMessage({
              type: 'error',
              message: '删除失败，请重试'
            })
          });
        done();
      } else {
        done();
      }
    },
  }).then((action) => { });

}
const getProgress = (row) => {
  // 根据row的状态字段返回进度条的百分比
  return row.status;
};
const formatProgress = (percentage) => {
  // 格式化进度条的文本显示
  return percentage === 100 ? "已完成" : `${percentage}%`;
};
let fileList = ref([]);
let uploadComplete = ref(false);
let uploadData = reactive({
  file_name: "",
  input_data: "",
});

let timeHandler = null;

const uploadFile = (options) => {
  showLoading("文件上传中...");
  const { onSuccess, file } = options; // 解构获取上传选项和文件对象
  const formData = new FormData();
  formData.append("file", file);
  formData.append("token", localStorage.getItem('accessToken'));
  hisRecord
    .uploadFile(formData)
    .then((res) => {
      // 1:正常；0:异常；
      loadingInstance.close();
      uploadRef.value.clearFiles();
      if (res && res.data.status) {
        if (res.data.status === "n") {
          ElMessage({
            message: "存在推理中的数据，请稍后再试！",
            type: "warning",
          });
        }
        if (res.data.status === "y") {
          ElMessage({
            message: "上传成功，正在推理中...",
            type: "success",
          });
          // onLoad()
          showLoading("数据推理中，请稍候...");
          timeHandler = setInterval(() => {
            getDataStatus();
          }, 5000);
        }
      }
    })
    .catch((err) => {
      uploadRef.value.clearFiles();
      loadingInstance.close();
      console.log(err);
    });
};
const emit = defineEmits(["tabVal", "changeStep"]);

const handleSuccess = (file, uploadFiles) => {
  console.log(file, uploadFiles);

  onLoad();
};
const handleError = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

let loadProgress = ref(0);
let progressFlag = ref(false);
const handleProgress = (event, file, fileList) => { };

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

let loadingInstance = null;
const showLoading = (textData) => {
  loadingInstance = ElLoading.service({
    text: textData,
    background: "rgba(0, 0, 0, 0.7)",
  });
};

const getDataStatus = () => {
  hisRecord.getStatus().then((res) => {
    if (res && res.data.status) {
      const status = res.data.status;
      if (status === "y") {
        // 推理完成：成功 or 失败
        loadingInstance.close();
        // ElMessage({
        //   message: '推理完毕！',
        //   type: 'success',
        // })
        clearInterval(timeHandler);
        timeHandler = null;
        onLoad();
        ElMessageBox.alert("推理完毕！", "", {
          // if you want to disable its autofocus
          // autofocus: false,
          center: true,
          confirmButtonText: "确定",
        });
      } else {
      }
    }
  });
};
</script>
<style scoped>
.box-content {
  position: relative;
  overflow: auto;
  padding: 10px;
  border-radius: 10px;
  height: 100%;
  background-color: #fff;
}

.page-box {
  margin: 20px 0 10px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload) {
  width: 100%;

}

.upload-box {
  text-align: center;
  margin-bottom: 10px;
  ;
  /* padding-right: 30px; */
  /* margin-top: 30px;
  padding-bottom: 30px; */
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
}

.button-div {

  /* display: flex;
  justify-content: center;
  margin: 10px auto; */
  .button_class {
    width: 100%;
  }

  .blue {
    background-color: #EAF3FF;
    color: #4494FC;
  }

  .gray {
    background-color: #F7F8FA;
    color: #4E5969;
  }
}

.el-tag {
  cursor: pointer;
  margin-right: 10px;
}
</style>
